//
//  CTCArticleDetailVC.m
//  ConsultantVersion
//
//  Created by 小龙 on 2017/4/10.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCArticleDetailVC.h"
#import "CTCArticleModel.h"
#import "CTCArticleCommentModel.h"
#import "CTCArticleDetailCell.h"
#import "CTCArticleCommentCell.h"
#import <WebKit/WebKit.h>

@interface CTCArticleDetailVC ()<UITableViewDataSource,
                                UITableViewDelegate,
                                UIWebViewDelegate,
                                CTCArticleDetailCellDelegate
                                >

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** <#strong属性注释#> */
@property (nonatomic, strong) CTCArticleDetailCell *articleDetailCell;

//@property (nonatomic, strong) CTCArticleModel *articleDetailModel;

/** <#strong属性注释#> */
@property (nonatomic, strong) NSMutableArray *commentArr;
/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger lastId;
@property (weak, nonatomic) IBOutlet BWHTextView *commentTextView;

/** 文章详细内容 */
@property (nonatomic, copy) NSString *articleContentStr;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentTextViewHeightLayout;
@end

@implementation CTCArticleDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.commentTextView.placeHolderText = @"请输入评论";
    
    self.lastId = 1;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCArticleDetailCell class]) bundle:nil] forCellReuseIdentifier:@"CTCArticleDetailCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCArticleCommentCell class]) bundle:nil] forCellReuseIdentifier:@"CTCArticleCommentCell"];
    
    self.tableView.estimatedRowHeight = 519;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore1)];
    [footer setTitle:@"点击加载更多评论" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在加载" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多评论" forState:MJRefreshStateNoMoreData];
    // 设置footer
    self.tableView.mj_footer = footer;
    
    [self loadHtml];
    [self loadNew];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.articleDetailCell stopLoading];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    [self.articleDetailCell stopLoading];
}


- (IBAction)sendCommentBtnClick
{
    [self sendComment];
}


- (void)loadHtml
{
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    [self.tableView reloadData];
    parames[@"uuid"] = self.articleModel.articleID;
    
    [RequestTool POST:kArticleDetailUrl parameters:parames progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DeLog(@"文章详情responseObject： %@", responseObject);
        if ([responseObject[@"code"]  integerValue] == 1) {
            [MBProgressHUD hideHUD];
            self.articleContentStr = responseObject[@"data"];
            [self.tableView reloadData];
            
        }
        else if ([responseObject[@"code"] intValue] == 2) {
            [MBProgressHUD showAnimationHUD];
            CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
            MPWeakSelf(self);
            vc.loginSuccess = ^(){
                [weakself loadHtml];
            };
            [self presentViewController:vc animated:YES completion:nil];
            
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"load html error  -- %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    if (self.commentArr.count) {
//        return 2;
//    }
//    return 1;
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    return self.commentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            if (!self.articleDetailCell) {
                CTCArticleDetailCell * cell = (CTCArticleDetailCell *)[tableView dequeueReusableCellWithIdentifier:@"CTCArticleDetailCell"];
                self.articleDetailCell = cell;
                if (self.isFromMyArticleVC) {
                    cell.deleteBtn.hidden = NO;
                }
                else {
                    cell.deleteBtn.hidden = YES;
                }
                
                self.articleDetailCell.delegate = self;
                
            }
            
            self.articleDetailCell.html = self.articleContentStr;
            self.articleDetailCell.articleModel = self.articleModel;
            
            return self.articleDetailCell;
            break;
        }
        case 1:
        {
            CTCArticleCommentCell *commCell = [tableView dequeueReusableCellWithIdentifier:@"CTCArticleCommentCell"];
            commCell.commentModel = self.commentArr[indexPath.row];
//            commCell.delegate = self;
            return commCell;
            break;
        }
        default:
            break;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0.f;
    switch (indexPath.section) {
        case 0:
        {
            CGSize size = [self.articleDetailCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
            height = size.height + 1 ;
            break;
        }
        case 1:
            height = [tableView fd_heightForCellWithIdentifier:@"CTCArticleCommentCell" configuration:^(CTCArticleCommentCell *cell) {
                cell.commentModel = self.commentArr[indexPath.row];
            }];
            break;
    }
    return height;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return @"精彩评论";
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 39;
    }
    return 0;
}



#pragma mark - JSBOriginalDetailCellDelegate
- (void)articleDetailCell:(CTCArticleDetailCell *)cell heightDidChange:(CGFloat)height
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        
    });
}



#pragma mark - 评论部分
- (void)loadNew
{
    [self.commentArr removeAllObjects];
//    [self.tableView reloadData];
    
    self.lastId = 1;
    [self.tableView.mj_footer resetNoMoreData];
    
    [self loadRequest];
}

- (void)loadMore1
{
    DeLog(@"加载更多");
    [self loadRequest];
}

- (void)loadRequest
{
    
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    parames[@"uuid"] = self.articleModel.articleID;
    parames[@"pageIndex"] = @(self.lastId);
    parames[@"pageEnd"] = @(self.lastId + 5);
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kArticleCommentListUrl parameters:parames progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        if (self.tableView.mj_header.isRefreshing) {
//            
//        }
//        
//        if (self.tableView.mj_footer.isRefreshing) {
//            
//        }
        
//        [self.tableView.mj_header endRefreshing];
//        [self.tableView.mj_footer endRefreshing];
        [self stopRefresh];
//        !self.tableView.mj_header.isRefreshing ? : [self.tableView.mj_header endRefreshing];
//        !self.tableView.mj_footer.isRefreshing ? : [self.tableView.mj_footer endRefreshing];
        
        DeLog(@"评论列表-----responseObject %@", responseObject);
        
        CTCArticleCommentListModel *listModel = [CTCArticleCommentListModel yy_modelWithJSON:responseObject];
        if ([listModel.code integerValue] == 1) {
            [MBProgressHUD hideHUD];
//            !self.tableView.mj_header.isRefreshing ? : [self.tableView.mj_header endRefreshing];
//            !self.tableView.mj_footer.isRefreshing ? : [self.tableView.mj_footer endRefreshing];
            
            if (!listModel.commentArr.count) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                return ;
            }
            
            [self.commentArr addObjectsFromArray:listModel.commentArr];
            self.lastId += self.commentArr.count;
            
            //1.传入要刷新的组数
//            NSIndexSet *indexSet=[[NSIndexSet alloc] initWithIndex:1];
//            //2.传入NSIndexSet进行刷新
//            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            
            [self.tableView reloadData];
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if ([listModel.code integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self stopRefresh];
        DeLog(@"评论列表-----error:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
    }];
}


// 发表评论 点赞
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    self.commentTextViewHeightLayout.constant = MIN(textView.contentSize.height, 110);
    
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [self sendComment];
        return NO;
    }
    return YES;
}

- (void)sendComment
{
    if (!self.commentTextView.text.length
        || !self.articleModel.articleID.length) {
        return;
    }
    
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    parames[@"uuid"] = self.articleModel.articleID;
    parames[@"content"] = self.commentTextView.text;
    parames[@"userType"] = @"1";
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kSendArticleCommentUrl parameters:parames progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"评论成功否-----responseObject   :%@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            [self.view endEditing:YES];
            self.commentTextView.text = @"";
            self.commentTextViewHeightLayout.constant = 40;
            
            [MBProgressHUD showSuccessMessage:responseObject[@"des"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadNew];
            });
            
            if (self.commentSuccessReturnBlcok) {
                self.commentSuccessReturnBlcok();
            }
            
            ++self.articleModel.discussNum;
            
        } else {
            
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            
            if ([responseObject[@"code"] integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"发送评论的错误-------%@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
        
    }];
    
}


-(NSMutableArray *)commentArr
{
    if (!_commentArr) {
        _commentArr = [NSMutableArray array];
    }
    
    return _commentArr;
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

- (void)articleDetailCellDeleteBtnClick:(CTCArticleDetailCell *)cell
{
    // UIAlertViewController(弹框视图)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确认删除这篇文章吗" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:cancel];
    
    
    UIAlertAction *confim = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteArticleRequest];
    }];
    [alert addAction:confim];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)deleteArticleRequest
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"uuid"] = self.articleModel.articleID;
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kDeleteArticleUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject:%@",responseObject);
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
            if (self.deleteMyArticleBlcok) {
                self.deleteMyArticleBlcok();
            }
            [kNotificationCenter postNotificationName:kReloadArticleListNotification object:nil];
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [MBProgressHUD showErrorMessage:responseObject[@"des"]];
            if ([responseObject[@"code"] integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"-----error:%@",error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

@end
